<template>
  <div
    ref="carouselContainer"
    class="carousel-container relative overflow-hidden"
    style="height: 330px"
    @touchstart="handleTouchStart"
    @touchmove="handleTouchMove"
    @touchend="handleTouchEnd"
    @wheel="handleWheel"
  >
    <!-- 轮播轨道 -->
    <div
      class="carousel-track flex transition-transform duration-500 ease-out"
      :style="{ transform: `translateX(${trackPosition}px)` }"
    >
      <!-- 轮播项 -->
      <div
        v-for="item in carouselList"
        :key="item.humanId"
        class="carousel-item flex-shrink-0 transition-all duration-500 ease-out"
        :class="{
          'opacity-70': item.humanId !== selectedId
        }"
        :style="{
          width: `${itemTotalWidth}px`,
          padding: `0 ${itemPadding}px`
        }"
        @click="selectImage(item.humanId)"
      >
        <div
          class="carousel-image-container flex justify-center items-center mx-auto relative rounded-10"
          :class="{ 'upload-img-box': Number(item.humanId) === 0 }"
          :style="{
            width: item.humanId === selectedId ? '290px' : '250px',
            height: item.humanId === selectedId ? '290px' : '250px'
          }"
        >
          <template v-if="Number(item.humanId) === 0">
            <div
              class="c-linear-purple px-6 leading-15 h-15 absolute top-0 right-0 rounded-tr-10 rounded-bl-8 text-10"
            >
              余{{ userAssetDetailData.humanBalance }}次
            </div>
            <svg-icon name="icon-shangchuan" :size="30" color="#fff" />
            <div class="mt-10 text-16">添加照片</div>
          </template>
          <template v-else>
            <van-image
              class="relative"
              :class="
                item.humanImgWidth > item.humanImgHigh ? 'w-full' : 'h-full'
              "
              radius="12"
              :fit="
                item.humanImgWidth > item.humanImgHigh ? 'cover' : 'contain'
              "
              :src="item.humanImageUrl"
            >
              <template
                v-if="item.humanTaskStatus == HUMAN_IMG_STATUS_ENUM.NO_SUBMIT"
              >
                <div
                  class="c-translucent-balck50 h-24 w-24 absolute right-10 top-10 rounded-6 flex items-center justify-center"
                >
                  <svg-icon name="icon-meihua" :size="16" color="#fff" />
                </div>
                <div
                  class="c-translucent-balck50 h-24 w-68 absolute right-10 bottom-10 rounded-6 flex items-center justify-center text-12"
                >
                  更换照片
                </div>
              </template>
            </van-image>
          </template>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from "vue";
import { UserAssetDetailData } from "@/api/MyHuman";
import { InfoListData } from "@/api/CreatePictureVideo";
import { HUMAN_IMG_STATUS_ENUM } from "@/enums";
const props = defineProps({
  carouselList: {
    type: Array as () => InfoListData[],
    default: () => []
  },
  selectedId: {
    type: String,
    default: "0"
  },
  // 资产信息
  userAssetDetailData: {
    type: Object as () => UserAssetDetailData,
    default: () => {}
  }
});

// emits
const emit = defineEmits<{
  (e: "update:selectedId", humanId: string): void;
}>();

// 轮播容器引用
const carouselContainer = ref<HTMLDivElement | null>(null);

// 轮播状态
const currentIndex = ref<number>(0);
const trackPosition = ref<number>(0);
const startX = ref<number>(0);
const startY = ref<number>(0); // 新增：记录起始Y坐标
const currentX = ref<number>(0);
const isDragging = ref<boolean>(false);
const isHorizontalDrag = ref<boolean | null>(null); // 新增：拖动方向标识

// 轮播项尺寸配置
const itemWidth = 290; // 最大项宽度
const itemPadding = 0; // 项之间的内边距
const itemTotalWidth = computed(() => itemWidth + itemPadding * 2); // 包含内边距的总宽度

// 计算当前选中项的索引
const getCurrentIndex = () => {
  return props.carouselList.findIndex(
    item => Number(item.humanId) === Number(props.selectedId)
  );
};

// 初始化当前索引
onMounted(() => {
  currentIndex.value = getCurrentIndex();
  updateTrackPosition();

  // 监听窗口大小变化，重新计算位置
  window.addEventListener("resize", updateTrackPosition);

  return () => {
    window.removeEventListener("resize", updateTrackPosition);
  };
});

// 当选中ID变化时更新索引和位置
watch(
  () => props.selectedId,
  () => {
    currentIndex.value = getCurrentIndex();
    updateTrackPosition();
  }
);

// 当图片列表变化时更新位置
watch(
  () => props.carouselList,
  () => {
    currentIndex.value = getCurrentIndex();
    updateTrackPosition();
  },
  { deep: true }
);

// 计算轮播轨道的位置
function updateTrackPosition() {
  if (!carouselContainer.value) return;

  const containerWidth = carouselContainer.value.offsetWidth;

  // 计算中心点偏移量，确保两侧显示部分相邻项
  const centerOffset = (containerWidth - itemTotalWidth.value) / 2;

  // 修正后的轨道位置计算
  trackPosition.value =
    centerOffset - currentIndex.value * itemTotalWidth.value;
}

// 选择图片
function selectImage(id: string) {
  emit("update:selectedId", id);
}

// 切换到上一张 - 修改：移除循环逻辑
function prevImage() {
  if (currentIndex.value > 0) {
    const prevItem = props.carouselList[currentIndex.value - 1];
    selectImage(prevItem.humanId);
    return true; // 成功切换
  }
  return false; // 在第一个，未切换
}

// 切换到下一张 - 修改：移除循环逻辑
function nextImage() {
  if (currentIndex.value < props.carouselList.length - 1) {
    const nextItem = props.carouselList[currentIndex.value + 1];
    selectImage(nextItem.humanId);
    return true; // 成功切换
  }
  return false; // 在最后一个，未切换
}

// 触摸开始处理
function handleTouchStart(e: TouchEvent) {
  startX.value = e.touches[0].clientX;
  startY.value = e.touches[0].clientY; // 记录起始Y坐标
  isDragging.value = true;
  isHorizontalDrag.value = null; // 重置方向标识
}

// 触摸移动处理 - 添加边界阻力效果
function handleTouchMove(e: TouchEvent) {
  if (!isDragging.value) return;

  const currentXVal = e.touches[0].clientX;
  const currentYVal = e.touches[0].clientY;
  const diffX = currentXVal - startX.value;
  const diffY = currentYVal - startY.value;

  // 判断拖动方向（仅首次移动时判断）
  if (isHorizontalDrag.value === null) {
    const isHorizontal = Math.abs(diffX) > Math.abs(diffY);
    isHorizontalDrag.value = isHorizontal;

    if (isHorizontal) {
      // 阻止默认行为（页面滚动）
      e.preventDefault();
    }
  }

  // 仅处理水平拖动
  if (isHorizontalDrag.value) {
    // 确保阻止默认行为
    e.preventDefault();

    currentX.value = currentXVal;
    const containerWidth = carouselContainer.value?.offsetWidth || 0;

    // 计算最大拖动距离（添加边界阻力）
    let maxDrag = containerWidth / 3;

    // 如果在第一个并且向右拖动（prev方向），减少最大拖动距离
    if (currentIndex.value === 0 && diffX > 0) {
      maxDrag = Math.min(maxDrag, 30); // 限制最大拖动距离为30px
    }

    // 如果在最后一个并且向左拖动（next方向），减少最大拖动距离
    if (currentIndex.value === props.carouselList.length - 1 && diffX < 0) {
      maxDrag = Math.min(maxDrag, 30);
    }

    const dragOffset = Math.max(Math.min(diffX, maxDrag), -maxDrag);

    // 添加拖动时的临时偏移
    trackPosition.value =
      (containerWidth - itemTotalWidth.value) / 2 -
      currentIndex.value * itemTotalWidth.value +
      dragOffset;
  }
}

// 触摸结束处理 - 修改：添加切换结果检测
function handleTouchEnd() {
  if (!isDragging.value) return;

  // 仅处理水平拖动
  if (isHorizontalDrag.value) {
    const diffX = currentX.value - startX.value;
    const threshold = 50; // 滑动阈值

    let switched = false;
    // 根据滑动距离决定切换方向
    if (diffX > threshold) {
      switched = prevImage(); // 尝试切换到上一张
    } else if (diffX < -threshold) {
      switched = nextImage(); // 尝试切换到下一张
    }

    // 如果没有切换（未达到阈值或边界限制），回到原位置
    if (!switched) {
      updateTrackPosition();
    }
  }

  // 重置状态
  isDragging.value = false;
  isHorizontalDrag.value = null;
}

// 鼠标滚轮处理 - 修改：添加边界检测
function handleWheel(e: WheelEvent) {
  e.preventDefault(); // 阻止页面滚动

  // 向上滚动 -> 上一张，向下滚动 -> 下一张
  if (e.deltaY < 0) {
    prevImage();
  } else {
    nextImage();
  }
}
</script>

<style scoped>
.carousel-container {
  padding: 20px 0;
  touch-action: pan-y; /* 允许垂直滚动 */
}

/* 禁用用户选择，防止滑动时选中内容 */
.carousel-container,
.carousel-track,
.carousel-item {
  user-select: none;
  -webkit-user-select: none;
}

/* 平滑滚动 */
.carousel-track {
  will-change: transform;
  transition-timing-function: cubic-bezier(0.25, 0.46, 0.45, 0.94);
}

.carousel-item {
  transition-timing-function: cubic-bezier(0.25, 0.46, 0.45, 0.94);
}

/* 确保图片过渡平滑 */
.carousel-image-container {
  transition: all 0.5s cubic-bezier(0.25, 0.46, 0.45, 0.94);
}

.upload-img-box {
  background-image: linear-gradient(139deg, #25253d 0%, #1d1d1f 100%);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: #fff;
  font-size: 16px;
}
.side-upload-img-box {
  z-index: 100;
  position: absolute;
  left: 0;
  top: 104px;
  width: 30px;
  height: 115px;
  background-image: linear-gradient(167deg, #6c3dff 0%, #0f07ff 100%);
  border-radius: 0 10px 10px 0;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: #fff;
  font-size: 13px;
  transition: all 1s;
  line-height: 16px;
}
</style>
